<template>
  <div class="flex">
    <div class="tableManage w-100%">
      <ContentWrap>
        <!-- <div class="search-form">
          <Search
            :schema="allSchemas.searchSchema"
            @reset="setSearchParams"
            @search="setSearchParams"
          />
        </div>

        <ElDivider /> -->


        <Table
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :columns="allSchemas.tableColumns"
          :data="dataList"
          :loading="loading"
          @register="tableRegister"
          :pagination="{
            total,
          }"
        />
      </ContentWrap>
    </div>
    <Dialog width="65%" v-model="dialogVisible" :title="dialogTitle">


      <Detail
        v-if="actionType === 'detail'"
        :detail-schema="allSchemas.detailSchema"
        :current-row="currentRow"
      />

      <template #footer>

        <BaseButton @click="dialogVisible = false"> 关闭 </BaseButton>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="tsx">

import {
  ref,
  unref,
  reactive,
  watch,
  computed,
  onMounted,
  defineProps,
  withDefaults,
  ComponentRef,
} from "vue";
import { ContentWrap } from "@/components/ContentWrap";
import { Table } from "@/components/Table";
import { useTable } from "@/hooks/web/useTable";
import { Search } from "@/components/Search";
import { useValidator } from "@/hooks/web/useValidator";
import Detail from "./components/dMeProductsDetail.vue";
import { Dialog } from "@/components/Dialog";
import { CrudSchema, useCrudSchemas } from "@/hooks/web/useCrudSchemas";
import { BaseButton } from "@/components/Button";
import { useDictionaryStore } from "@/store/modules/dictionaryStore";
import {  View } from "@element-plus/icons-vue";


const { required } = useValidator();

const dictionaryStore = useDictionaryStore();
interface CurrentNodeTask {
  deviceCode?: string;
  deviceName?: string;
  missionCode?: string;
  // 根据实际需要添加其他属性
}
interface Props {
  currentNodeTask?: CurrentNodeTask;
  type?: string;
}
// 使用 withDefaults 设置默认值
const props = withDefaults(defineProps<Props>(), {
  currentNodeTask: () => ({}),
  type: undefined
});
// 使用计算属性确保值的安全性
const safeCurrentNodeTask = computed(() =>
  props.currentNodeTask && typeof props.currentNodeTask === 'object'
    ? props.currentNodeTask
    : {}
);
const deviceCode = ref(safeCurrentNodeTask.value.deviceCode ?? '');
const currentNodeName = ref(safeCurrentNodeTask.value.deviceName ?? '');
const missionCode = ref(safeCurrentNodeTask.value.missionCode ?? '');



const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState;


    if (!deviceCode.value || !missionCode.value) {
      return {
        list: [],
        total: 0,
      };
    }
     const collectorUserCode = localStorage.getItem("collectorUserCode");
    const res = await "/cDomesticElectromechanicals/page".get({
      deviceCode: deviceCode.value,
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
        createby: collectorUserCode || "",
      missionCode: missionCode.value,
      isLockTask:1,
      ...unref(searchParams),
    });
    return {
      list: res.data.records || [],
      total: res.data.total || 0,
    };
  },

});
const { total, loading, dataList, pageSize, currentPage } = tableState;
const { getList } = tableMethods;

// 监听 props 变化
watch(
  () => props.currentNodeTask,
  (newVal, oldVal) => {
    try {
      console.log(newVal, oldVal, "currentNodeTask");
      deviceCode.value = newVal?.deviceCode ?? '';
      currentNodeName.value = newVal?.deviceName ?? '';
      missionCode.value = newVal?.missionCode ?? '';
      // 只有在有设备代码时才调用 getList
      if (newVal?.deviceCode) {
        getList();
      }
    } catch (error) {
      console.error('Error in currentNodeTask watcher:', error);
      // ElMessage.error('数据加载失败');
    }
  },
  { immediate: true } // 添加 immediate 确保初始执行
);
/**
 * 处理类别选择变化
 * @param value 选中的值数组
 * @param selectedOptions 选中的选项对象数组
 */

const getCascaderObj = (val, opt) => {
  return val.map(function (value, index, array) {
    for (var itm of opt) {
      if (itm.code == value) {
        opt = itm.children;
        return itm;
      }
    }
    return null;
  });
};

const handleCategoryChange = (value) => {
  console.log(value);

  const selectedOptions = getCascaderObj(
    value,
    dictionaryStore.dictionaries.get(
      dictionaryStore.DICTIONARY_TYPES.ELE_CLASSIFICATION
    )
  );
  if (!currentRow.value) {
    currentRow.value = {};
  }

  // // // 清空之前的分类数据
  currentRow.value.classification1 = "";
  currentRow.value.classification2 = "";
  currentRow.value.classification3 = "";
  currentRow.value.classificationCode = "";
  currentRow.value.category = value;
  currentRow.value.classificationCode =
    selectedOptions[selectedOptions.length - 1].code;
  // // // 根据选中的层级设置对应的分类字段
  if (selectedOptions.length > 0) {
    currentRow.value.classification1 = selectedOptions[0]?.text || "";
  }
  if (selectedOptions.length > 1) {
    currentRow.value.classification2 = selectedOptions[1]?.text || "";
  }
  if (selectedOptions.length > 2) {
    currentRow.value.classification3 = selectedOptions[2]?.text || "";
  }
};

/**
 * 元器件分类选项
 */
const classificationOptions = computed(() => {
  return (
    dictionaryStore.dictionaries.get(
      dictionaryStore.DICTIONARY_TYPES.COM_CLASSIFICATION
    ) || []
  );
});
/**
 * 是否核关高选项
 */
const isHighlyCriticalOptions = computed(() => {
  return (
    dictionaryStore.dictionaries.get(dictionaryStore.DICTIONARY_TYPES.YORN) ||
    []
  );
});
// 自主可控等级
const controllableOptions = computed(() => {
  return (
    dictionaryStore.dictionaries.get(
      dictionaryStore.DICTIONARY_TYPES.INDEPENDENT_CONTROL_LEVEL
    ) || []
  );
});
// 是否核心关键高端产品
const coreKeyOptions = computed(() => {
  return (
    dictionaryStore.dictionaries.get(dictionaryStore.DICTIONARY_TYPES.YORN) ||
    []
  );
});
// 使用分类
const usageClassificationOptions = computed(() => {
  return dictionaryStore.dictionaries.get(
    dictionaryStore.DICTIONARY_TYPES.USAGE_CLASSIFICATION
  ) || [];
});

/**
 * 根据分类名称查找对应的分类代码
 * @param names 分类名称数组 [一级名称, 二级名称, 三级名称]
 * @returns 分类代码数组
 */
const findCategoryCodesByName = (names: string[]): string[] => {
  const { DICTIONARY_TYPES } = dictionaryStore;
  const categoryOptions = dictionaryStore.dictionaries.get(DICTIONARY_TYPES.MA_CLASSIFICATION) || [];

  const result: string[] = [];
  let currentLevel = categoryOptions;

  for (let i = 0; i < names.length; i++) {
    const name = names[i];
    if (!name) break;

    const found = currentLevel.find(item => item.text === name);
    if (found) {
      result.push(found.code);
      currentLevel = found.children || [];
    } else {
      // 如果没有找到匹配项，停止查找
      break;
    }
  }

  return result;
};
/**
 * 根据行数据构建级联选择器数据
 * @param row 行数据
 * @returns 级联选择器数据数组
 */
const buildCategoryData = (row: any): string[] => {
  // 如果已经有分类代码，直接返回处理过的数据
  if (row.classificationCode) {
    return row.classificationCode.length == 8
      ? [
          row.classificationCode.slice(0, 4),
          row.classificationCode.slice(0, 6),
          row.classificationCode,
        ]
      : row.classificationCode.length == 6
        ? [
            row.classificationCode.slice(0, 4),
            row.classificationCode.slice(0, 6),
          ]
        : [row.classificationCode.slice(0, 4)];
  }

  // 如果没有分类代码，根据分类名称查找
  const names = [
    row.classification1,
    row.classification2,
    row.classification3
  ].filter(Boolean); // 过滤掉空值

  if (names.length > 0) {
    return findCategoryCodesByName(names);
  }

  return [];
};
// 在子组件中添加这个方法
const findDeviceNameByCode = (deviceCode: string) => {
  console.log('deviceCode', deviceCode,props.currentNodeTask);

  if (!deviceCode || !props.currentNodeTask) return '';

  // 递归查找设备名称
  const findInTree = (nodes: any[]): string => {
    for (const node of nodes) {
      if (node.deviceCode === deviceCode) {
        return node.deviceName || '';
      }
      if (node.children && node.children.length > 0) {
        const result = findInTree(node.children);
        if (result) return result;
      }
    }
    return '';
  };

  return findInTree([props.currentNodeTask]);
};
const crudSchemas = reactive<CrudSchema[]>([
 {
    field: "selection",
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    table: { type: "selection", hidden: true },
  },
  {
    field: "index",
    label: "序号",
    form: { hidden: true },
    search: { hidden: true },
    detail: { hidden: true },
    table: { type: "index" },
  },
  {
    field: "account",
    label: "所属设备",
    width: 90,
    search: { hidden: true },
    form: {
      component: "Input",
      value: currentNodeName.value,
      componentProps: {
        placeholder: "请输入所属设备",
        disabled: true,
      },
    },
    table: { hidden: true },
  },
  {
    field: "classificationCode",
    width: 100,
    label: "分类代码",
    form: {
      hidden:true,
      componentProps: {
        placeholder: "分类代码将自动生成",
        disabled: true,
      },
      formItemProps: { rules: [required()] },
    },
    detail:{
      hidden:true,
    },
    table:{
      hidden:true,
    },
    search: {
      component: "Input",
      label: "",
      hidden: true,
      componentProps: { placeholder: "分类代码" },
    },
  },
  {
    field: "category",
    label: "类别",
    width: 250,
    search: {
      component: "Cascader",
      componentProps: {
        placeholder: "类别",
        options: classificationOptions,
        filterable: true,
        props: {
          checkStrictly: false,
          emitPath: true,
          label: "text",
          value: "code",
        },
      },
    },
    form: {
      component: "Cascader",
      formItemProps: {
        rules: [{ required: true, message: "请选择类别" }],
      },
      componentProps: {
        placeholder: "请选择类别",
        filterable: true,
        options: classificationOptions,
        props: {
          checkStrictly: false,
          emitPath: true,
          label: "text",
          value: "code",
        },
        onChange: (value: any[]) => {
          handleCategoryChange(value);
        },
      },
    },
    detail: { hidden: true },
    table: {
         formatter: (row: any) => {
        // 组合分类字段，用 > 分隔，空值用 / 代替
        const parts = [
          row.classification1 || "/",
          row.classification2 || "/",
          row.classification3 || "/",
        ];
         return parts.join(" > ");
      },
    },
  },
  {
    field: "classification1",
    label: "一级类别",
    width: 90,
    search: { hidden: true },
    form: { hidden: true },
    table: { hidden: true },
  },
  {
    field: "classification2",
    label: "二级类别",
    width: 90,
    search: { hidden: true },
    form: { hidden: true },
    table: { hidden: true },
  },
  {
    field: "classification3",
    label: "三级类别",
    width: 90,
    search: { hidden: true },
    form: { hidden: true },
    table: { hidden: true },
  },
  {
    field: "productStandardNo",
    label: "产品标准编号",
    width: 120,
    form: {
      componentProps: { placeholder: "请输入产品标准编号" },
      formItemProps: {
        rules: [
          { required: true, message: "请输入产品标准编号" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入产品标准编号" },
        ],
      },
    },
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: { placeholder: "产品标准编号" },
    },
  },
  {
    field: "productStandardName",
    label: "产品标准名称",
    width: 120,
    form: {
      componentProps: { placeholder: "请输入产品标准名称" },
      formItemProps: {
        rules: [
          { required: true, message: "请输入产品标准名称" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入产品标准名称" },
        ],
      },
    },
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: { placeholder: "产品标准名称" },
    },
  },
  {
    field: "productName",
    label: "产品名称",
    width: 150,
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: { placeholder: "产品名称" },
    },
    form: {
      component: "Input",
      componentProps: { placeholder: "请输入产品名称" },
      formItemProps: {
        rules: [
          { required: true, message: "请输入产品名称" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入产品名称" },
        ],
      },
    },
  },
  {
    field: "modelSpecification",
    label: "型号规格",
    width: 80,
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: { placeholder: "型号规格" },
    },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入型号规格" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入型号规格" },
        ],
      },
      componentProps: { placeholder: "请输入型号规格" },
    },
  },
  {
    field: "quantityPerDevice",
    label: "单个设备使用数量",
    width: 90,
    search: { hidden: true },
    table: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入单个设备使用数量" },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                return callback(new Error("输入值不能低于 0"));
              }
              callback();
            },
          },
        ],
      },
      componentProps: {
        type: "number",
        placeholder: "请输入单个设备使用数量",
        min: 0,
      },
    },
  },
  //   {
  //   field: "isWkb",
  //   label: "是否WKB",
  //   width: 90,
  //   form: {
  //     component: "Select",
  //     value: "",
  //     componentProps: { options: isWkbOptions },
  //     formItemProps: {
  //       rules: [{ required: true, message: "请选择是否WKB" }],
  //     },
  //   },
  //   search: { hidden: true },
  // },
  //  {
  //   field: "isPre",
  //   label: "是否优选",
  //   width: 90,
  //   form: {
  //     hidden: true
  //   },
  //   search: { hidden: true },
  // },
  {
    field: "referencePrice",
    label: "单件价格(元)",
    width: 120,
    search: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入参考价格" },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                return callback(new Error("输入值不能低于 0"));
              }
              callback();
            },
          },
        ],
      },
      componentProps: {
        type: "number",
        placeholder: "请输入参考价格",
        min: 0,
      },
    },
  },
  {
    field: "coreFunctionalIndicators",
    label: "核心功能指标",
    width: 90,
    search: { hidden: true },
    table: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入核心功能指标" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入核心功能指标" },
        ],
      },
      componentProps: { placeholder: "请输入核心功能指标" },
    },
    detail: { span: 24 },
  },
    {
    field: "usageClassification",
    label: "使用分类",
    width: 150,
    search: { hidden: true },
    form: {
      component: "Select",
      formItemProps: {
        rules: [
          { required: true, message: "请输入使用分类" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入使用分类" },
        ],
      },
      componentProps: { placeholder: "请选择使用分类", options: usageClassificationOptions },
    },
  },


  {
    field: "manufacturer",
    label: "生产厂商",
    width: 150,
    search: {
      component: "Input",
      label: "",
      hidden: true,
      componentProps: { placeholder: "生产厂商" },
    },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入生产厂商" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入生产厂商" },
        ],
      },
      componentProps: { placeholder: "请输入生产厂商" },
    },
  },
    {
    field: "isCoreElectromechanicals",
    label: "是否核心关键高端产品",
    width: 180,
    form: {
      component: "Select",
      value: "是",
      componentProps: { options: coreKeyOptions },
      formItemProps: {
        rules: [{ required: true, message: "请选择是否核心关键高端产品" }],
      },
    },
    search: {
      component: "Select",
      label: "是否核心关键高端产品",
      hidden: false,
      componentProps: {
        placeholder: "是否核心关键高端产品",
        options: coreKeyOptions,
      },
    },
  },
    {
    field: "independentControlLevel",
    label: "自主可控等级",
    width: 120,
    search: {
      component: "Select",
      label: "自主可控等级",
      hidden: false,
      componentProps: {
        placeholder: "自主可控等级",
        options: controllableOptions,
      },
    },
    form: {
      component: "Select",
      value: "",
      formItemProps: {
        rules: [{ required: true, message: "请选择自主可控等级" }],
      },
      componentProps: { options: controllableOptions },
    },
  },
  // {
  //   field: "isNuclearHighControl",
  //   label: "是否核关高",
  //   width: 120,
  //   form: {
  //     component: "Select",
  //     value: "",
  //     formItemProps: {
  //       rules: [{ required: true, message: "请选择是否核关高" }],
  //     },
  //     componentProps: { options: isHighlyCriticalOptions },
  //   },
  //   search: {
  //     component: "Select",
  //     label: "是否核关高",
  //     hidden: false,
  //     componentProps: {
  //       placeholder: "是否核关高",
  //       options: isHighlyCriticalOptions,
  //     },
  //   },
  // },

  {
    field: "personInCharge",
    label: "负责人",
    search: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [{ required: true, message: "请输入负责人" }],
      },
      componentProps: { placeholder: "请输入负责人" },
    },
  },
  {
    field: "contactInfo",
    label: "联系方式",
    width: 120,
    search: { hidden: true },
    form: {
      component: "Input",
      componentProps: { placeholder: "请输入联系方式" },
      formItemProps: {
        rules: [
          { required: true, message: "请输入联系方式" },
          { pattern: /^[0-9]{11}$/, message: "请输入正确的联系方式" },
        ],
      },
      colProps: { span: 24 },
    },
    detail: { span: 12 },
  },
  {
    field: "remarks",
    label: "备注",
    width: 90,
    search: { hidden: true },
    detail: { span: 24 },
    form: {
      component: "Input",
      componentProps: {
        type: "textarea",
        rows: 3,
        placeholder: "请输入备注信息",
      },
      colProps: { span: 24 },
    },
    table: { hidden: true },
  },
  {
    field: "action",
    label: "操作",
    fixed: "right",
    form: {
      hidden: true,
    },
    detail: {
      hidden: true,
    },
    search: {
      hidden: true,
    },
    table: {
      width: 80,
      fixed: "right", // 这里也需要添加
      slots: {
        default: (data: any) => {
          const row = data.row;
          return (
            <>
              <div style="display:flex;color: var(--el-color-primary)">

                <div
                  class="flex-1 cursor-pointer"
                  onClick={() => action(row, "detail")}
                >
                  {" "}
                  <el-icon>
                    <View />
                  </el-icon>
                  查看
                </div>

              </div>
            </>
          );
        },
      },
    },
  },
]);

const { allSchemas } = useCrudSchemas(crudSchemas);

const searchParams = ref({
  classificationCode: "",
});
const setSearchParams = (params: any) => {
  currentPage.value = 1;
  searchParams.value = params;
  searchParams.value.classificationCode =
    params.category?.[params.category.length - 1] || "";

  getList();
};

const dialogVisible = ref(false);
const dialogTitle = ref("");

const currentRow = ref();
const actionType = ref("");





const action = (row: any, type: string) => {
  dialogTitle.value = type === "edit" ? "编辑" : "查看";

  actionType.value = type;
   const categoryData = buildCategoryData(row);

 // 根据 deviceCode 查找设备名称
  const deviceName = findDeviceNameByCode(row.deviceCode);
  currentRow.value = {
    ...row,
    category: categoryData,
    classificationCode:categoryData[categoryData.length - 1] || "",
    account: deviceName, // 使用查找到的设备名称
  };
  dialogVisible.value = true;
};






onMounted(async () => {
  // 检查是否有有效数据
  if (safeCurrentNodeTask.value.deviceCode && safeCurrentNodeTask.value.missionCode) {
    getList();
  }
});
</script>

<style scoped lang="less">
.el-card {
  // overflow-x: auto;
  //  --el-card-border-color {

  //  }
}
.operIcon {
  width: 20px !important;
}
:deep(.el-divider--horizontal) {
  margin: 5px 0 15px 0;
}
.mb-10px {
  display: flex;
}
.opBtn-upload {
  display: inline-block;
  margin: 0 12px;
}
:deep(.el-card__body ){
  padding: 10px  0 !important;
}
</style>
